<template>
    <div id="container">
        <my-header></my-header>
        <div id="main">
            <el-container id="main-container">
                <el-aside id="aside">
                    <span id="title">项目基本信息</span>
                    <el-divider></el-divider>
                    <div id="basic-info">
                        <h1>{{project.name}}</h1>
                        <span class="text">{{project.desc}}</span>
                        <el-divider id="divider-inner"></el-divider>
                        <div id="info" class="text"><i class="el-icon-reading"></i>&nbsp;{{project.course}}</div>
                        <div id="info" class="text"><i class="el-icon-time"></i>&nbsp;开始时间：{{project.start_time}}</div>
                        <div id="info" class="text"><i class="el-icon-time"></i>&nbsp;结束时间：{{project.end_time}}</div>
                        <div id="info" class="text">
                            <i class="el-icon-turn-off"></i>
                            项目状态：
                            <el-switch
                                v-model="project.status"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                disabled>
                            </el-switch>
                        </div>
                        <div id="member-list">
                              <el-table
                                :data="project.member"
                                style="width: 100%">
                                <el-table-column
                                label="项目成员">
                                    <template slot-scope="scope">
                                        <i class="el-icon-user"></i>
                                        <span>{{scope.row.id}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column>
                                    <template slot-scope="scope">
                                        <div slot="reference" class="name-wrapper">
                                            <el-tag size="medium" :type="scope.row.isOwner ? 'warning' : 'primary'">{{ scope.row.name }}</el-tag>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div id="control">
                            <el-button type="success" round @click="setEnterprise" v-if="this.$store.state.login.role === 2">设置为企业项目</el-button>
                            <el-button type="primary" round @click="finish" v-if="project.status">完成该项目并申报资产</el-button>
                        </div>
                        
                    </div>
                </el-aside>
                <el-main id="right">
                    <span id="title">项目资产目录</span>
                    <el-button type="success" round icon="el-icon-circle-plus-outline" id="upload-button" size="medium" @click="invate" v-if="project.status">邀请项目成员</el-button>
                    <el-button type="primary" round icon="el-icon-upload2" id="upload-button" size="medium" @click="uploadFormVisible = true">资产上传</el-button>
                    <el-divider></el-divider>
                    <el-breadcrumb separator-class="el-icon-arrow-right">
                        <el-breadcrumb-item v-for="(item,index) in this.$store.state.levels" :key="item.id" :to="{path:item.path}">{{item.name}}</el-breadcrumb-item>
                    </el-breadcrumb>
                    <router-view></router-view>
                </el-main>
            </el-container>
        </div>
        <my-footer></my-footer>
        <!-- 资产上传模态框 -->

        <el-dialog title="资产上传" :visible.sync="uploadFormVisible">
            <el-form :model="uploadForm" :rules="uploadRules" ref="form">
                <el-form-item label="资产名称" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="uploadForm.name" autocomplete="off" placeholder="请输入资源名称"></el-input>
                </el-form-item>
                <el-form-item label="版本号" :label-width="formLabelWidth" prop="version">
                    <el-input v-model="uploadForm.version" autocomplete="off" placeholder="例如：1.0"></el-input>
                </el-form-item>
                <el-form-item label="资源类型" :label-width="formLabelWidth" prop="type">
                    <el-select v-model="uploadForm.type" placeholder="请选择资源类型">
                        <el-option label="WORD文档" value="word"></el-option>
                        <el-option label="PPT演示文稿" value="ppt"></el-option>
                        <el-option label="EXCEL表格" value="excel"></el-option>
                        <el-option label="图片" value="photo"></el-option>
                        <el-option label="PDF文档" value="pdf"></el-option>
                        <el-option label="软件/程序/源代码" value="program"></el-option>
                        <el-option label="压缩包" value="compress"></el-option>
                        <el-option label="音频" value="audio"></el-option>
                        <el-option label="视频" value="video"></el-option>
                        <el-option label="TXT文本文档" value="txt"></el-option>
                        <el-option label="ISO镜像文件" value="iso"></el-option>
                        <el-option label="网页/URL" value="url"></el-option>
                        <el-option label="其他" value="unkown"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文件上传" :label-width="formLabelWidth">
                    <el-upload
                        class="upload-demo"
                        drag
                        action=""
                        :file-list="fileList"
                        :auto-upload="false"
                        :multiple="false"
                        ref="upload"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :on-remove="handleRemove"
                        >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">不限制文件类型，大小不超过500MB<br/>只支持单文件上传，若您有多个文件，请先将其打包为压缩包</div>
                    </el-upload>
                    <el-progress :percentage="percentage" :status="upload_status" v-if="percentage_visibility"></el-progress>
                    <el-button type="primary" size="mini" id="upload-button-inner" @click="submitUpload">上传<i class="el-icon-upload el-icon--right"></i></el-button>
                </el-form-item>
                <el-form-item label="资源描述" :label-width="formLabelWidth" prop="desc">
                    <el-input type="textarea" v-model="uploadForm.desc"></el-input>
                </el-form-item>
                <el-form-item label="软件过程阶段" :label-width="formLabelWidth" prop="stage">
                    <el-select v-model="uploadForm.stage" placeholder="请选择资源类型">
                        <el-option label="通用" value="通用"></el-option>
                        <el-option label="分析阶段" value="分析"></el-option>
                        <el-option label="设计阶段" value="设计"></el-option>
                        <el-option label="实现阶段" value="实现"></el-option>
                        <el-option label="测试阶段" value="测试"></el-option>
                        <el-option label="维护阶段" value="维护"></el-option>
                        <el-option label="本资源不适用此分类" value="不适用"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属课程" :label-width="formLabelWidth" prop="course">
                    <el-input v-model="uploadForm.course" autocomplete="off" placeholder='请输入所属课程名称，多个课程适用请填写"通用"'></el-input>
                </el-form-item>
                <el-form-item label="入库至" :label-width="formLabelWidth" prop="location">
                    <div class="block">
                        <el-cascader
                            v-model="uploadForm.location"
                            :options="options"
                            :props="props"
                            ></el-cascader>
                    </div>
                </el-form-item>
                <el-form-item label="标签" :label-width="formLabelWidth" prop="tags">
                    <el-input v-model="uploadForm.tags" autocomplete="off" placeholder="以空格分开"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="uploadFormVisible = false">取 消</el-button>
                <el-button type="primary" :disabled="!upload_success_tag" @click="commit">提交审核</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import MyFooter from '../../components/MyFooter.vue'
import MyHeader from '../../components/MyHeader.vue'
import axios from 'axios';
export default {
    name:'ProjectDetail',
    data:function() {
        return{
            project:{},
            uploadForm: {
                name: '',
                version:'',
                type:'',
                stage:'',
                course:'通用',
                desc:'',
                location:'',
                tags:''
            },
            formLabelWidth: '120px',
            uploadFormVisible:false,
            uploadRules:{
                name: [
                    { required: true, message: '请输入资产名称', trigger: 'blur' },
                    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
                ],
                version:[
                    {required: true,message: '请输入版本号', trigger: 'blur'},
                    {
                        validator:function(rule, value, callback){
                            let reg = /^\d+(\.\d+)?$/;
                            if(!reg.test(value)){
                                callback('只能输入数字和小数点，只允许存在一层子版本号，例如：2.1');
                            }else{
                                callback();
                            }
                        }
                    }
                ],
                type:[
                    { required: true, message: '请选择资产类型', trigger: 'blur' }
                ],
                stage:[
                    { required: true, message: '请选择软件工程阶段', trigger: 'blur' }
                ],
                course: [
                    { required: true, message: '请输入所属课程名称', trigger: 'blur' },
                    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                ],
                desc:[
                    { required: true, message: '请输入资产描述', trigger: 'blur' },
                    { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' }
                ],
                location:[
                    { required: true, message: '请选择该资产的上传位置', trigger: 'blur' }
                ],
                tags:[
                    { required: true, message: '请输入至少2个标签', trigger: 'blur' },
                    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
                ]
            },
            // 文件上传
            fileList:[],
            // 上传进度
            percentage:0,
            upload_status:null,
            percentage_visibility:false,
            // 文件上传成功标志位
            upload_success_tag:false,
            // 文件上传回执信息
            upload_callback:null,
            // 级联选择框
            props: {
                lazy: true,
                lazyLoad :((node, resolve) => {
                    let that = this;
                    setTimeout( async() => {
                        let children = [];
                        const res = await axios.get('/api/common/structure?fid='+node.value+'&project_id='+this.$route.query.project_id+'&type=1');
                        if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                        if(res.data.res.ok === 1){
                            // 构造children
                            for(let i in res.data.res.data){
                                // 判断是否为叶子节点
                                const current_res = await axios.get('/api/common/structure?fid='+res.data.res.data[i].fid+'&project_id='+this.$route.query.project_id+'&type=1');
                                if(current_res.status!==200) return this.$message.error("请求失败，请检查网络设置！")
                                let temp = '';
                                if(current_res.data.res.ok === 0){
                                    // 如果是叶子节点
                                    temp = {'value':res.data.res.data[i].fid,'label':res.data.res.data[i].name,'leaf':'leaf'};
                                }else{
                                    // 如果不是叶子节点
                                    temp = {'value':res.data.res.data[i].fid,'label':res.data.res.data[i].name};
                                }
                                children.push(temp);
                            }
                        }else{
                            children.push({'value':node.value.toString(),'label':node.label+"(自身)",'leaf':'leaf'});
                            // that.uploadForm.location = node.value.toString();
                        }
                        // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                        resolve(children);
                    }, 1000);
                })
            },
        }
    },
    // computed:{
    //     query:function(){
    //         return this.$route.query;
    //     }
    // },
    components: { MyHeader, MyFooter},
    methods:{
        submitUpload:function() {
            console.log(this.fileList);
            console.log(this.uploadForm);
            //this.$refs.upload.submit();
            this.$message('上传成功！');
        },
        getQuery:function(){
            return this.$route.query;
        },
        getProjectDetail:async function(){
            const headerConfig = { headers:
                { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
                const res = await axios.get('/api/project/project_detail?project_id='+this.$route.query.project_id,headerConfig);
                if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                if(res.data.res.ok === 1){
                    this.project = res.data.res.data;
                }else{
                    this.$notify({
                        title: '提示',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                    this.$router.push('/project');
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        // 获取该文件夹的字文件夹和文件
        getContent:async function(id){
            const headerConfig = { headers:
                { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
            };
            try{
                const res = await axios.get('/api/project/basic_content',headerConfig);
                if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                if(res.data.res.ok === 1){
                    this.project = res.data.res.data;
                }else{
                    this.$notify({
                        title: '提示',
                        message: res.data.res.msg,
                        type: 'error'
                    });
                }
            }catch(e){
                console.log(e);
                this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
            }
        },
        // 资源上传方法
        submitUpload:function() {
            console.log(this.uploadForm);
            this.percentage_visibility = true;
            const formData = new FormData();
            const file = this.$refs.upload.uploadFiles[0];
            const headerConfig = { headers:
                { 'Content-Type': 'multipart/form-data' ,'x-auth-token': this.$store.state.login.token},
                onUploadProgress: progressEvent => {
                    if(progressEvent.lengthComputable){
                        let val = parseInt(
                            (
                                (progressEvent.loaded / progressEvent.total)*100
                            ).toFixed(0)
                        );//获取百分比
                        this.percentage = val;
                        if(val == 100){
                            this.upload_status = 'success';
                        }
                    }
                }
            }
            if (!file) { // 若未选择文件
                alert('请选择文件')
                return
            }
            formData.append('file', file.raw)
            axios.post('/api/upload/single', formData, headerConfig).then(res => {
                //console.log(res);
                this.$notify({
                    title: '提示',
                    message: res.data.res.msg,
                    type: res.data.res.status
                });
                if(res.data.res.ok === 1){
                    this.upload_success_tag = true;
                    this.upload_callback = res.data.res;
                }
            })
        },
        handleExceed(files, fileList) {
            this.$message.warning(`只允许选择1个文件，若有多个文件需要上传，请打包为压缩包后再上传！`);
        },
        handleRemove(file, fileList){
            this.percentage = 0;
            this.percentage_visibility = false;
        },
        commit:function(){
            this.$refs.form.validate(async (valid) => {
                if(!valid) {
                    this.$message.error("信息为填写完整或未按要求填写，请根据红色文字提示修改后再进行提交！");
                    return;
                }
                // let location = 0;
                // if(this.$data.uploadForm.location.length > 1){
                //     location = this.$data.uploadForm.location[this.$data.uploadForm.location.length-1];
                // }else{
                //     location = this.$data.uploadForm.location;
                // }
                let post_data = {
                    name:this.$data.uploadForm.name,
                    version:this.$data.uploadForm.version,
                    type:this.$data.uploadForm.type,
                    uploader:this.$store.state.login.uid,
                    stage:this.$data.uploadForm.stage,
                    course:this.$data.uploadForm.course,
                    desc:this.$data.uploadForm.desc,
                    location:this.$data.uploadForm.location[this.$data.uploadForm.location.length-1],
                    tags:this.$data.uploadForm.tags,
                    originalname:this.upload_callback.originalname,
                    path:this.upload_callback.path,
                    size:this.upload_callback.size,
                    project_id:this.$route.query.project_id,
                    request_type:1
                }
                const headerConfig = { headers:
                    { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
                };
                try{
                    const res = await axios.post('/api/upload/file_info_commit',post_data,headerConfig);
                    if(res.status!==200) return this.$message.error("提交失败，请检查网络设置！");
                    if(res.data.res.ok === 1){
                        this.$notify({
                            title: '提交成功',
                            message: "提交成功！您上传的资源正在等待管理员审核，审核结果可以在'我的——个人中心——消息中心'中找到",
                            type: 'success'
                        });
                    }else{
                        this.$notify({
                            title: '提交失败',
                            message: res.data.res.msg,
                            type: 'error'
                        });
                    }
                }catch(e){
                    console.log(e);
                    this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
                }
            });
            this.uploadFormVisible = false;
        },
        // 邀请项目成员
        invate:function(){
            this.$prompt('请输入您要邀请的用户名', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern: /^[0-9\u4e00-\u9fffa-zA-Z]{3,30}$/,
              inputErrorMessage: '请输入长度3-30字符的合法用户名'
            }).then(async ({ value }) => {
                let post_data = {
                    username:value,
                    project_id:this.$route.query.project_id
                }
                const headerConfig = { headers:
                    { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
                };
                try{
                    const res = await axios.post('/api/project/invate',post_data,headerConfig);
                    if(res.status!==200) return this.$message.error("提交失败，请检查网络设置！");
                    if(res.data.res.ok === 1){
                        this.$notify({
                            title: '成功',
                            message: res.data.res.msg,
                            type: 'success'
                        });
                    }else{
                        this.$notify({
                            title: '失败',
                            message: res.data.res.msg,
                            type: 'error'
                        });
                    }
                }catch(e){
                    console.log(e);
                    this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
                }
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消输入'
              });       
            });
        },
        finish:function(){
            this.$confirm('此操作将会变更本项目的状态并将项目资产入库和公开，是否继续？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
            }).then(async () => {
                let post_data = {
                    project_id:this.$route.query.project_id
                }
                const headerConfig = { headers:
                    { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
                };
                try{
                    const res = await axios.post('/api/project/finish',post_data,headerConfig);
                    if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                    if(res.data.res.ok === 1){
                        this.$notify({
                            title: '提示',
                            message: res.data.res.msg,
                            type: 'success'
                        });
                    }else{
                        this.$notify({
                            title: '提示',
                            message: res.data.res.msg,
                            type: 'error'
                        });
                    }
                }catch(e){
                    console.log(e);
                    this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });          
            });
        },
        setEnterprise:function(){
              this.$confirm('此操作将会把该项目设置为【企业项目】，是否继续？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
            }).then(async () => {
                let post_data = {
                    project_id:this.$route.query.project_id
                }
                const headerConfig = { headers:
                    { 'Content-Type': 'application/json' ,'x-auth-token': this.$store.state.login.token}
                };
                try{
                    const res = await axios.post('/api/project/setEnterprise',post_data,headerConfig);
                    if(res.status!==200) return this.$message.error("请求失败，请检查网络设置！");
                    if(res.data.res.ok === 1){
                        this.$notify({
                            title: '提示',
                            message: res.data.res.msg,
                            type: 'success'
                        });
                    }else{
                        this.$notify({
                            title: '提示',
                            message: res.data.res.msg,
                            type: 'error'
                        });
                    }
                }catch(e){
                    console.log(e);
                    this.$message.error("出错了！这不是您的问题，我们的工程师正在努力修复！");
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });          
            }); 
        }
    },
    mounted(){
        this.getProjectDetail();
    }
}
</script>

<style lang="scss" scoped>
#container{
    width: 100%;
    // height: 100%;
    background-color: #eee;
    #main{
        width:100%;
        min-height: 700px;
        padding-top:40px;
        padding-left: 15%;
        padding-right: 15%;
        background-color:#eee;
        box-sizing: border-box;
        #main-container{
            width:100%;
            height: 100%;
            #aside{
                width:30%;
                background-color: #fff;
                padding:20px;
                margin-bottom:50px;
            }
            #basic-info{
                margin-top:30px;
                margin-left: 5px;
                h1{
                    font-size: 20px;
                    margin-bottom:10px;
                }
                .text{
                    display: block;
                    margin-top:13px;
                    font-size: 14px;
                    line-height: 20px;
                    color:gray;
                }
                #info{
                    // margin-top:15px;
                    font-size: 15px;
                }
                #divider-inner{
                    margin:20px;
                    margin-left: 0;
                }
            }
            #right{
                width:70%;
                background-color: #fff;
                margin-left:20px;
                padding:20px;
                margin-bottom:50px;
            }
            #title{
                color: #2267c7;
                font-size: 18px;
                display: inline-block;
                margin-bottom: 10px;
                margin-left: 5px;
            }
        }
    }
}
/deep/ .el-divider{
    margin: 10px;
}
.el-breadcrumb{
    margin-top:20px;
    margin-left: 5px;
}
#upload-button{
    float:right;
    margin-right: 20px;
}
#control{
    margin-top:20px;
}
</style>